/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package master.proyectoweb.managedbeans;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import master.proyectoweb.ejb.CustomerOrderFacade;
import master.proyectoweb.entities.CustomerOrder;
import master.proyectoweb.entities.OrderedProduct;
import master.proyectoweb.entities.OrderedProductPK;
import master.proyectoweb.entities.Product;
import master.proyectoweb.entities.User;
import master.proyectoweb.managedbeans.util.JsfUtil;

/**
 *
 * @author joaquin
 */
@Named("basketController")
@SessionScoped
public class BasketController implements Serializable {
    
    private CustomerOrder customerOrder;
    private OrderedProduct orderedProduct;
    private List<OrderedProduct> listProducts;
    private int numProducts;
    private String ccard;
    @EJB
    private master.proyectoweb.ejb.CustomerOrderFacade ejbFacade;

    /**
     * Creates a new instance of BasketController
     */
    public BasketController() {
        customerOrder = new CustomerOrder();
        orderedProduct = new OrderedProduct();
        listProducts = new ArrayList<>();
    }
    
    public String gotoBasket() {
        String res;
        User user = (User)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("currentUser");
        
        if(user != null){
            res = "basket";
        }
        else{
            res = "access";
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/resources/webtext").getString("auth_error"));
        }
        
        return res;
    }
    
    public String addToBasket(){
        String res;
        User user = (User)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("currentUser");
        if(user != null){
            res = "#";
            updateCustomerOrder(user);
            
            //restart the orderedProduct object
            orderedProduct = new OrderedProduct();
        }
        else{
            res = "access";
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/resources/webtext").getString("auth_error"));
        }
        
        return res;
    }
 
    private void updateCustomerOrder(User user) {
        OrderedProduct order;
        int index;
        
        if(customerOrder.getUserId() == null){
            customerOrder.setUserId(user);
        }
        
        if(!listProducts.contains(orderedProduct)){            
            listProducts.add(orderedProduct);
        }   
        
        //get the orderedProduct (maybe optional)
        index = listProducts.indexOf(orderedProduct);
        order = listProducts.get(index);
        
        //update the quantity attribute of the orderedProduct
        order.setQuantity((short) (order.getQuantity()+1));
        
        //recalculate total amount of the order
        customerOrder.setAmount(customerOrder.getAmount().add(orderedProduct.getProduct().getPrice()));
        numProducts++;
    }
    
    public void addOne() {
        orderedProduct.setQuantity((short) (orderedProduct.getQuantity()+1));
        customerOrder.setAmount(customerOrder.getAmount().add(orderedProduct.getProduct().getPrice()));
        numProducts++;
    }
    
    public void susOne() {
        if(orderedProduct.getQuantity() > 1){
            orderedProduct.setQuantity((short) (orderedProduct.getQuantity()-1));
            customerOrder.setAmount(customerOrder.getAmount().subtract(orderedProduct.getProduct().getPrice()));
            numProducts--;
        }
    }
    
    public void removeProduct() {
        BigDecimal price,quantity,updatedPrice;
               
        price = orderedProduct.getProduct().getPrice();        
        quantity = new BigDecimal(orderedProduct.getQuantity());
        
        updatedPrice = price.multiply(quantity);        
        customerOrder.setAmount(updatedPrice);
        
        numProducts = numProducts - orderedProduct.getQuantity();
        
        listProducts.remove(orderedProduct);
    }
    
    public String checkout() {
        return "payment";
    }
    
    public String finishOrder() {
        
        /*TODO process payment data*/
        
        try {
            getFacade().createOrder(customerOrder,listProducts);
            System.out.println("number: "+customerOrder.getConfirmationNumber());
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/webtext").getString("order_complete"));
            
            //clean the fields to get ready for a new order
            customerOrder = new CustomerOrder();
            listProducts = new ArrayList<>();
            numProducts = 0;
            
            return "order_confirm";
            
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/webtext").getString("order_error"));
            return null;
        }
    }
    
    
    private CustomerOrderFacade getFacade() {
        return ejbFacade;
    }
     
    public CustomerOrder getCustomerOrder() {
        return customerOrder;
    }

    public void setCustomerOrder(CustomerOrder customerOrder) {
        this.customerOrder = customerOrder;
    }

    public OrderedProduct getOrderedProduct() {
        return orderedProduct;
    }

    public void setOrderedProduct(OrderedProduct orderedProduct) {
        this.orderedProduct = orderedProduct;
    }

    public int getNumProducts() {
        return numProducts;
    }

    public String getCcard() {
        return ccard;
    }

    public void setCcard(String ccard) {
        this.ccard = ccard;
    }

    public List<OrderedProduct> getListProducts() {
        return listProducts;
    }
}
